<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="/error.jsp"%>
<%@page import="dbexp.model.Table"%>
<%@page import="dbexp.model.db.DbUser"%>
<%@page import="dbexp.connection.DbMetaData"%>
<%@page import="java.util.Vector"%>
<%@page import="dbexp.model.Row"%>
<%@page import="java.util.List"%>
<%@page import="dbexp.model.Column"%>
<%@page import="org.json.JSONArray"%>
<%@page import="java.util.Iterator"%>
<%@page import="org.json.JSONObject"%>
<%@page import="dbexp.model.TableData"%>
<%
DbUser u = (DbUser)session.getAttribute("USER");													//pobieramy uzytkownika z sesji
String name = request.getParameter("name").toUpperCase();										//pobieramy nazwe tabeli z zadania
String schema = request.getParameter("schema").toUpperCase();								//pobieramy nazwe schematu z zadania

boolean nowy = (name==null || name.trim().equals("null")) && (schema==null || schema.trim().equals("null"));
String id = schema+"-"+name;																							///ustawiamy id dla kontrolek
Table t = null;
	JSONArray reader_jsoncs = new JSONArray();
	JSONArray grid_jsoncs = new JSONArray();
if(!nowy){
	t = DbMetaData.getTable(u, name.toUpperCase(), schema.toUpperCase());
	List<Column> columns = t.getColumns();
	reader_jsoncs.put( new JSONObject().put("name","NR"));
	JSONObject grid_jsonc = new JSONObject();
	grid_jsonc.put("header", "NR");
	grid_jsonc.put("width",20);
	grid_jsonc.put("sortable",true);
	grid_jsoncs.put(grid_jsonc);
	for (Column column : columns) {
		JSONObject reader_prop = new JSONObject();
		JSONObject grid_prop = new JSONObject();
		reader_prop.put("name", column.getName().toLowerCase());
		grid_prop.put("header", column.getName().toLowerCase());
		grid_prop.put("width",180);
		grid_prop.put("sortable",true);
		grid_prop.put("editor","textField");
		grid_prop.put("dataIndex",column.getName().toLowerCase());
		if(column.isNullable()){
			reader_prop.put("allowBlank", false);
		}
		grid_jsoncs.put(grid_prop);
		reader_jsoncs.put(reader_prop);
	}
}
String save = "Zapisz";
if(nowy){
	save = "Utwórz";
}
%>
<div class="container">
    <div id="<%=id%>-table-data-grid"></div>
</div>
<script type="text/javascript"">
var proxy = new Ext.data.HttpProxy({
    api: {
	    read : {url:'db/table/data/read.jsp',method:'POST'},
	    create :{url:'db/table/data/create.jsp',method:'POST'},
	    update: {url:'db/table/data/update.jsp',method:'POST'},
	    destroy: {url:'db/table/data/delete.jsp',method:'POST'}
    }
});

var reader = new Ext.data.JsonReader({
    totalProperty: 'total',
    successProperty: 'success',
    idProperty: 'NR',
    root: 'data'
},  <%=reader_jsoncs.toString()%>);
function change(val){
    if(val > 0){
        return '<span style="color:green;">' + val + '</span>';
    }else if(val < 0){
        return '<span style="color:red;">' + val + '</span>';
    }
    return val;
}
var writer = new Ext.data.JsonWriter({
    encode: true,
    writeAllFields: false
});

var store = new Ext.data.Store({
    remoteSort: true,
    baseParams: {name:'<%=name %>', schema:'<%=schema %>',action:''},
    autoLoad: {params:{start:0, limit:50}},
    proxy: proxy,
    reader: reader,
    writer: writer,
    autoSave: false,
    batch:true,
    listeners: {
        write : function(store, action, result, res, rs) {
    		Ext.Msg.alert('akcja',action);
        },
        exception : function(proxy, type, action, options, res, arg) {
            if (type === 'remote') {
                Ext.Msg.show({
                    title: 'REMOTE EXCEPTION',
                    msg: res.message,
                    icon: Ext.MessageBox.ERROR,
                    buttons: Ext.Msg.OK
                });
            }
        }
    }
});

var textField =  new Ext.form.TextField();
//store.load();
var tableColumns = new Ext.grid.ColumnModel(<%=grid_jsoncs.toString().replaceAll("\"editor\":\"textField\"","editor:textField")%>);
TableDataGrid = Ext.extend(Ext.grid.EditorGridPanel, {
    renderTo: '<%=id%>-data-grid',
    border:false,
    frame: true,
    height:350,

    initComponent : function() {
        this.relayEvents(this.store, ['destroy', 'save', 'update']);

        this.tbar = this.buildTopToolbar();
        this.buttons = this.buildUI();

        TableDataGrid.superclass.initComponent.call(this);
    },

    buildTopToolbar : function() {
        return [{
            text: 'Dodaj',
            iconCls: 'silk-add',
            handler: this.onAdd,
            scope: this
        }, '-', {
            text: 'Usuń',
            iconCls: 'silk-delete',
            handler: this.onDelete,
            scope: this
        }, '-'];
    },

    buildUI : function() {
        return [{
            text: 'Zapisz',
            iconCls: 'icon-save',
            handler: this.onSave,
            scope: this
        }];
    },
    onSave : function(btn, ev) {
        this.store.save();
    },
    onAdd : function(btn, ev) {
        var u = new this.store.recordType({});
        this.stopEditing();
        this.store.insert(0, u);
        this.startEditing(0, 1);
    },

    onDelete : function(btn, ev) {
        var index = this.getSelectionModel().getSelectedCell();
        if (!index) {
            return false;
        }
        var rec = this.store.getAt(index[0]);
        this.store.remove(rec);
    }
});
Ext.onReady(function() {
	try{
    var userGrid = new TableDataGrid({
        renderTo:"<%=id%>-table-data-grid",
        store: store,
        layout:'fit',
        trackMouseOver:false,
        viewConfig:{forceFit:false},
        cm :tableColumns ,
	    bbar: new Ext.PagingToolbar({
		    store: store,
		    pageSize:50,
		    displayInfo:true
	    }),
	    listeners: {
            rowclick: function(g, index, ev) {
                var rec = g.store.getAt(index);
            },
            destroy : function() {
            	tableForm.getForm().reset();
            }
        }
    });
	}catch(e){alert(e);}
});
</script>